import React, { useState, useEffect } from 'react';
import { Modal, Input, Tabs, Button, Row, Col, Tag, Image, Spin, Badge, Tooltip } from 'antd';
import moment from 'moment';
import { PlanItemParam } from '../data';
import DeviceComponent from '../../Equipment/components/DeviceComponent';
import styles from '../index.less';

interface CreateFormProps {
  modalVisible: boolean;
  approvedLoading:boolean;
  rejectLoading:boolean;
  onApproved: (values: PlanItemParam) => void;
  onReject: (values: PlanItemParam) => void;
  onCancel: () => void;
  values:PlanItemParam;
}

const { TabPane } = Tabs;

const PlanReviewModel: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, approvedLoading, onApproved, rejectLoading, onReject, onCancel, values } = props;
  const [ tab, setTab] = useState<string>("1");
  const [ loading, setLoading] = useState<boolean>(false);
  const [ selectedTags, setSelectedTags] = useState<[]>([0]);
  const [ list, setList] = useState<[]>([]);
  const [ showList, setShowList] = useState<[]>([]);
  const [ playTimeList, setPlayTimeList] = useState<[]>([]);//循环时间段
  const [ type1, setType] = useState<string>("day"); //循环类型 每月/每周
  const [ playList1, setPlayList] = useState<[]>([]); //循环类型 每月/每周

  const callback = (key:string) => {
    setTab(key);
  }

  const typeList = {
    day:"每天",
    month:"每月",
    week:"每周",
  }
  const weekTrans = {
    Monday:"星期一",
    Tuesday:"星期二",
    Wednesday:"星期三",
    Thursday:"星期四",
    Friday:"星期五",
    Saturday:"星期六",
    Sunday:"星期日",
  }

  useEffect(() => {
    if(modalVisible){
      if(values && values.playConfig){
        setLoading(true);
        let type = "day";
        let playList = [];//循环类型 每月/每周
        let programList = [];//节目列表
        let playtimelist = [];
        const playConfig = JSON.parse(values.playConfig);
        // console.log(playConfig)
        if(playConfig[0]){
          type = playConfig[0].type;//循环类型 每天 每月 每周
          console.log(type)
          setType(playConfig[0].type);
          for(let i in playConfig){
            if(type){//按时段播放
              const list = playConfig[i][type];
              if(list){//每周 每月 用于循环类型后面的周几和几号
                playList = playList.concat(list);
              }
              const obj = new Object();
              const array = [];
              for(let j in playConfig[i].programList){
                array.push(playConfig[i].programList[j].id);
              }
              // console.log(playConfig[i])
              obj["id"] = array;
              obj["time"] = playConfig[i].startTime+"~"+playConfig[i].endTime;
              obj[type] = playConfig[i][type];
              playtimelist.push(obj);
            }
            programList = programList.concat(playConfig[i].programList);
          }
          setPlayTimeList(playtimelist);
          
          if(playList.length > 0){//去重
            const res = new Map();
            playList = playList.filter((a) => !res.has(a) && res.set(a, 1))
          }
          console.log(playList)
          setPlayList(playList);
          
          if(programList.length > 0){
            let obj = {};
            programList = programList.reduce((cur,next) => {
              obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
              return cur;
            },[]);
            setList(JSON.parse(JSON.stringify(programList)));
            setTimeout(function(){
              setLoading(false);
            },100);
          }
        }
      }
    }else{
      setSelectedTags([0]);
    }
  },[modalVisible,values]);

  useEffect(() => {
    const tag = document.querySelector("."+styles.PlanReviewModel)?.
      querySelector(".durantion")?.
      querySelector(".ant-tag"); //querySelector方法仅仅返回匹配指定选择器的第一个元素 
    if(tag){
      tag.click();
    }

  },[playTimeList]);

  const selectProgram = (value:any,index:number) =>{
    const ids = value.id;
    setSelectedTags([index]);
    if(value.week){
      setPlayList(value.week);
    }else if(value.month){
      setPlayList(value.month);
    }
    setLoading(true);
    const array = [];
    for(let i in list){
      for(let j in ids){
        if(list[i].id === ids[j]){
          array.push(list[i].id);
        }
      }
    }
    setShowList(array);
    setTimeout(function(){
      setLoading(false);
    },100);
  }

  const renderContent = () => {
    return (
      <>
      <Tabs onChange={callback} type="card" className={styles.PlanReviewModel}>
        <TabPane tab="计划详情" key="1">
          <Row>
            <Col span={12} style={{display:'flex'}}><strong>计划名称：</strong><span style={{width:'80%'}}>{values?.name}</span></Col>
            <Col span={12}><strong>播放日期：</strong>{values?.playDatetime}</Col>
          </Row>
          <Row>
            <Col span={12}><strong>发布方式：</strong>{values?.publishWay?.toString()?(values.publishWay == 0?"实时发布":"定时发布"):null}</Col>
            <Col span={12}><strong>发布时间：</strong>{values?.publishWay == 0?(values?.auditStatus == 1?moment(values?.auditDatetime).format('YYYY-MM-DD HH:mm:ss'):"--"):(values?.publishDatetime? moment(values.publishDatetime).format('YYYY-MM-DD HH:mm:ss'):"默认时间")}</Col>
          </Row>
          <Row>
            <Col span={12}><strong>发布类型：</strong>{values?.publishType?.toString()?(values.publishType == 0?"独立发布":"同步发布"):null}</Col>
            <Col span={12}><strong>默认计划：</strong>{values?.defaultPlan?.toString()?(values.defaultPlan == 0?"否":"是"):null}</Col>
          </Row>
          <Row>
            <Col span={12}><strong>播放模式：</strong>{values?.playMode?.toString()?(values.playMode == 0?"持续播放":"按时段播放"):null}</Col>
            <Col span={12}><strong>审核状态：</strong>{values?.auditStatus?.toString()?(values.auditStatus == 0?<Badge status="processing" text="待审核" />:values.auditStatus==1?<Badge status="success" text="已通过" />:<Badge status="error" text="已拒绝" />):null}</Col>
          </Row>
          <Row>
            <Col span={12}><strong>创建时间：</strong>{moment(values?.createDatetime).format('YYYY-MM-DD HH:mm:ss')}</Col>
            <Col span={12}><strong>发布状态：</strong>{values?.publishStatus?.toString()?
              (
                values.publishStatus == 0?<Badge status="default" text="待发布" />:
                  values.publishStatus==1?<Badge status="processing" text="发布中" />:
                    values.publishStatus==2?<Badge status="success" text="已发布" />:
                      values.publishStatus==3?<Badge status="warning" text="部分成功" />:
                        values.publishStatus==4?<Badge status="error" text="失败" />:<Badge status="default" text="结束" />
              ):null}</Col>
          </Row>
          <Row>
              <Col span={24} style={{display:"flex"}}>
                <strong style={{flex:'none',width:70}}>描述：</strong>
                <span>{values?.description}</span>
              </Col>
          </Row>
          <Row>
            <Col span={24} style={{display:"flex"}}>
              <strong>播放时段：</strong>
              <div>{values?.playMode?.toString()?(values.playMode == 0?"持续播放":(
                <>
                  <div style={{marginBottom:5}}>按时段播放</div>
                  <div style={{marginBottom:5}}>
                    循环类型：{values?.playConfig?typeList[type1]:null}
                    <span style={{display:'inline-block', marginLeft:10}}>
                      {playList1.map((item,index) =>  
                        <Tag key={index} color="blue" style={{marginBottom:4}}>{type1=="week"?weekTrans[item]:type1=="month"?item+"号":null}</Tag>)
                      }
                    </span>
                  </div>
                  <div style={{marginBottom:5}}>
                    循环时间段：
                      <span className="durantion" style={{marginLeft:10}}>
                        {playTimeList.map((item,index) =>  
                          <Tag 
                            key={index}
                            ids={item.id}
                            className={selectedTags.indexOf(index) > -1?"selected":""}
                            color="blue"
                            style={{cursor:"pointer"}}
                            onClick={()=>{console.log(item);selectProgram(item,index)}}>
                              {item.time}
                          </Tag>)
                        }
                    </span>
                  </div>
                </>
              )):null}</div>
            </Col>
            <Col span={24} className={styles.playInterval}>
              <strong>已选节目：</strong>
              <div className="content right" style={{marginLeft:0,height:"auto",boxShadow:"none"}}>
                <Spin spinning={loading}>
                  <div className="scroll" style={{width:"max-content"}}>
                    <ul>
                      {list.map((item,index) =>
                          <li key={index} style={{marginBottom:0, display:values.playMode == 0?"block":(showList.length>0?(showList.indexOf(item.id)>-1?"block":"none"):"block")}}>
                              <Image src={item.previewImgUrl} preview={false} />
                              <div className="mask">
                                  <Tooltip placement="topLeft" title={item.name}>
                                    <span className="name">{item.name}</span>
                                  </Tooltip>
                                  <p>
                                      <span>{item.resolution}</span>
                                      <span>{item.totalTime}秒</span>
                                  </p>
                              </div>
                          </li>
                      )}
                    </ul>
                  </div>
                </Spin>
              </div>
            </Col>
          </Row>
          <Row>
              <Col span={24}>
                <strong>原因：</strong>
                <Input.TextArea
                  className="auditReason"
                  rows={4} 
                  readOnly={values?.auditStatus==0?false:true}
                  style={{resize:"none"}} 
                  maxLength={256} 
                  defaultValue={values?.auditReason}
                />
              </Col>
          </Row>
        </TabPane>
        <TabPane tab="设备详情" key="2" className="device">
          <DeviceComponent
            type={"plan"}
            data={[]}
            planCode={values?.code}
            deviceIds={[]} 
            setDeviceIds={(deviceIds)=>console.log(deviceIds)}
          />
        </TabPane>
      </Tabs>
      </>
    );
  };

  return (
    <Modal
      destroyOnClose
      title=""
      width={1000}
      centered
      visible={modalVisible}
      onCancel={() => onCancel()}
      footer={[
        <>
        <Button key="cancel" onClick={onCancel}>返回</Button>
        {values?.auditStatus==0 && values?.type=="review"?(
          <>
          <Button type="primary" key="pass" loading={approvedLoading} onClick={() =>{
            const auditReason = document.getElementsByClassName("auditReason")[0].innerHTML;
            values.auditReason = auditReason;
            onApproved(values);
          }}>通过</Button>
          <Button type="primary" key="reject" loading={rejectLoading} danger onClick={() => {
            const auditReason = document.getElementsByClassName("auditReason")[0].innerHTML;
            values.auditReason = auditReason;
            onReject(values);
          }}>驳回</Button>
          </>
        ):(null)}
        </>
      ]}
    >
      {renderContent()}
    </Modal>
  );
};

export default PlanReviewModel;
